<template>
    <view class="layout">
        <!-- 导航栏 -->
        <view class="navbar">
            <view class="statusBar" :style="{height:getStatusBarHeight()+'px'}"></view>
            <view class="titleBar" :style="{height:getTitleBarHeight()+'px',marginLeft:getLeftIconLeft()+'px'}" >
                <view class="icon" @click="goBack">
                    <uni-icons type="left" size="30"></uni-icons>
                </view>
                <view class="title">
                    <text>Ai文生图</text>
                </view>
            </view>
        </view>
        <!-- 填充区域 -->
        <view class="fill" :style="{height:getNavBarHeight() +'px'}"></view>
    </view>
    
    <view class="style-title">生成风格</view>
    <scroll-view class="scroll-view_h" scroll-x scroll-with-animation :show-scrollbar="false">
        <view class="stytle-content" v-for="(item,index) in styleList" :key="index" 
        :class="{'select-style': selectIndex === index}" >
            <view class="style-list" @click="selectStyle(index)">
                <image :src="item.img" mode="aspectFill"></image>
                <text :style="{'backgroundColor':item.color}">{{item.title}}</text>
            </view>
        </view>
    </scroll-view>
    
    <!-- 比例选择器 -->
    <view class="ratio-title">选择比例 ({{ selectedWidth }}:{{ selectedHeight }})</view>
    <scroll-view class="scroll-view_h" scroll-x scroll-with-animation :show-scrollbar="false">
        <view class="ratio-content" v-for="(ratio, index) in aspectRatios" :key="index" 
        :class="{'select-ratio': selectedRatio === index}" @click="selectRatio(index)">
            <text>{{ratio}}</text>
        </view>
    </scroll-view>
    
    <!-- 多行文本输入框 -->
   <view class="section">
     <view class="section-title">画面关键词</view>
     <view class="input-container">
       <textarea 
         class="input-box" 
         placeholder="请输入图片内容描述" 
         maxlength="500"
         v-model="imageQuery.content"
       />
       <view class="input-footer">
         <view 
           class="word-count-container"
           @click="clearInput"
         >
             <!-- 智能扩写按钮 -->
             <view class="ai-expansion" @click.stop="expandContent" v-if="imageQuery.content.trim() !== ''" 
             :style="{'opacity': isExpanding ? '0.5' : '1', 'pointer-events': isExpanding ? 'none' : 'auto'}">
                 <text class="ai-text">智能扩写</text>
             </view>
             <view class="t">
                 <text>{{ imageQuery.content.length }}/500</text>
                 <uni-icons type="refresh" size="20"></uni-icons>
             </view>
         </view>
       </view>
     </view>
   </view>
   
    <!-- 生成效果提示 -->
    <view class="creative-tips" v-if="isGenerating">
        <view class="animating-text">
            <span v-for="(char, index) in charList" :key="index" :style="{ 
                color: currentIndex === index ? '#FFD700' : '#333', 
                marginRight: '10rpx' 
            }">{{ char }}</span>
        </view>
    </view>

    <view class="creative-images">
        <view class="creative-image" v-for="(img, index) in generatedImages" :key="index">
            <image 
                :src="img" 
                mode="widthFix" 
                @click="previewImage(img)"
            ></image>
            <view class="image-actions">
                <view class="action-button" @click.stop="deleteImage(index)">
                    <uni-icons type="trash" size="24" color="white"></uni-icons>
                </view>
                <view class="action-button" @click.stop="showSharePopup(img)">
                    <uni-icons type="redo" size="24" color="white"></uni-icons>
                </view>
                <view class="action-button" @click.stop="downloadImage(img)">
                    <uni-icons type="download" size="24" color="white"></uni-icons>
                </view>
            </view>
        </view>
    </view>
    
    <!-- 分享弹窗 -->
    <view>
        <uni-popup ref="sharePopup" type="share" safeArea backgroundColor="#fff">
            <view class="share-content">
                <view class="share-title">分享到</view>
                <view class="share-icons">
                    <view class="share-icon" @click="shareToWeixin">
                        <uni-icons type="weixin" size="30" color="#07C160"></uni-icons>
                        <text>微信</text>
                    </view>
                    <view class="share-icon" @click="shareToWeibo">
                        <uni-icons type="weibo" size="30" color="#E6162D"></uni-icons>
                        <text>微博</text>
                    </view>
                    <view class="share-icon" @click="shareToQQ">
                        <uni-icons type="qq" size="30" color="#00B4F4"></uni-icons>
                        <text>QQ</text>
                    </view>
                    <view class="share-icon" @click="shareToTimeline">
                        <uni-icons type="redo" size="30" color="#FFD700"></uni-icons>
                        <text>朋友圈</text>
                    </view>
                </view>
            </view>
        </uni-popup>
    </view>
    
    <!-- 提交完成 -->
    <button 
        class="btn" 
        :disabled="isButtonDisabled"
        @click="generateImage"
    >
        生成图片
    </button>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from "vue"
import { getStatusBarHeight, getTitleBarHeight, getNavBarHeight, getLeftIconLeft } from "@/utils/system.js"
import { ApiGetImage} from "/pages/api/image.js"
import { Apicustomer } from "/pages/api/common.js"

// 返回
const goBack = () => {
    uni.navigateBack()
}

// 使用 reactive 定义 imageQuery
const imageQuery = reactive({
    width: 512,
    height: 512,
    type: "无风格",
    content:"",
	url:""
})
// 初始化请求头
const header = ref({}); // 确保 header 是一个对象
onMounted(()=>{
	// 初始化 header
	header.value["access-token"] = uni.getStorageSync("token");
})

const selectIndex = ref(0)
const selectedRatio = ref(0)

const styleList = ref([
    {
        img: "/static/image/picture/1.jpg",
        title: "无风格",
        color: '#1F9BE5'
    },
    {
        img: "/static/image/picture/2.jpg",
        title: "动漫风格",
        color: '#4F965E'
    },
    {
        img: "/static/image/picture/3.jpg",
        title: "写实",
        color: '#93726F'
    },
    {
        img: "/static/image/picture/4.jpg",
        title: "Q版简绘",
        color: '#204251'
    },
    {
        img: "/static/image/picture/5.jpg",
        title: "治愈男主",
        color: '#656565'
    },
    {
        img: "/static/image/picture/6.jpg",
        title: "治愈女生",
        color: '#D49D7D'
    },
    {
        img: "/static/image/picture/7.jpg",
        title: "卡通手绘",
        color: '#ff9999'
    },
    {
        img: "/static/image/picture/8.jpg",
        title: "复古动漫",
        color: '#ffcc66'
    },
    {
        img: "/static/image/picture/9.jpg",
        title: "港风胶片",
        color: '#cc3300'
    }
])

const aspectRatios = ref(["1:1", "3:4", "4:3", "9:16"])

const selectedWidth = ref(1)
const selectedHeight = ref(1)


const generatedImages = ref([])

const animationInterval = ref(null);

const getImage = async () => {
    try {
        let res = await ApiGetImage(imageQuery)
        generatedImages.value = res
        isGenerating.value = false // 生成完成后隐藏提示
        clearInterval(animationInterval.value);
        isButtonDisabled.value = true
    } catch (error) {
        console.error("图片生成失败:", error);
        isGenerating.value = false;
        clearInterval(animationInterval.value);
    }
}

const isGenerating = ref(false)
const currentIndex = ref(0)
const charList = ref(['图', '片', '正', '在', '生', '成', '中', '.', '.', '.'])

const startAnimation = () => {
    isGenerating.value = true
    currentIndex.value = 0
    animationInterval.value = setInterval(() => {
        currentIndex.value = (currentIndex.value + 1) % charList.value.length
    }, 300)
}

const generateImage = () => {
    if (!isButtonDisabled.value) {
        startAnimation()
        getImage()
        isButtonDisabled.value = true
    }
}

// 预览图片
const previewImage = (currentImage) => {
    uni.previewImage({
        current: currentImage,
        urls: generatedImages.value
    });
}

// 删除图片
const deleteImage = (index) => {
    generatedImages.value.splice(index, 1)
}

const sharePopup = ref(null)

const showSharePopup = (img) => {
    currentImage.value = img
    sharePopup.value.open()
}

const shareToWeixin = () => {
    uni.setClipboardData({
        data: currentImage.value,
        success: () => {
            uni.showToast({
                title: "链接已复制",
                icon: "none"
            });
        }
    });
    sharePopup.value.close();
}

const shareToWeibo = shareToWeixin;
const shareToQQ = shareToWeixin;
const shareToTimeline = shareToWeixin;

const currentImage = ref(null)

const downloadImage = (imgUrl) => {
    uni.downloadFile({
        url: imgUrl,
        success: (res) => {
            if (res.statusCode === 200) {
                uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: () => {
                        uni.showToast({
                            title: "图片已保存",
                            icon: "none"
                        })
                    },
                    fail: (err) => {
                        console.error("保存图片失败:", err)
                    }
                })
            }
        },
        fail: (err) => {
            console.error("下载图片失败:", err)
        }
    })
}

const upload = (val)=>{
	uni.uploadFile({
	  url: '/api/app/file/upload', // 替换为你的上传接口地址
	  filePath: val,
	  name: 'file',
	  header: header.value, // 确保 header 是一个对象
	  success: async(uploadRes) => {
	    const data = JSON.parse(uploadRes.data);
	    if (data.code === 200) {
			imageQuery.url = data.data
	    } 
	 }
	});
}



const selectStyle = (index) => {
    selectIndex.value = index
    const selectedStyle = styleList.value[index]
    imageQuery.type = selectedStyle.title
}

const selectRatio = (index) => {
    selectedRatio.value = index
    const selectedRatioStr = aspectRatios.value[index]
    const [width, height] = selectedRatioStr.split(':')
    selectedWidth.value = width
    selectedHeight.value = height
    
    const baseWidth = 512
    imageQuery.width = baseWidth
    imageQuery.height = (baseWidth * height) / width
}

// 清除输入框内容
const clearInput = () => {
    imageQuery.content = ""
}

// 智能扩写功能
const expandContent = async() => {
    if (imageQuery.content.trim() !== '' && !isExpanding.value) {
        isExpanding.value = true; // 设置状态为正在扩写

        // 显示提示框
        uni.showToast({
            title: "正在智能扩写...",
            icon: "loading",
            duration: 5000
        });

        // 构建提示词
        const content = "请根据我提供的提示词" + imageQuery.content.trim() + ",帮我对这个提示词进行优化.用中文你只要回复优化后的提示词就可以其他的不用回复"
        let res = await Apicustomer(content)
		// 扩写完成后恢复状态
		isExpanding.value = false;
        imageQuery.content = res;
    }
}

// 按钮禁用状态
const isButtonDisabled = ref(true);

// 监听 imageQuery 的变化
watch(imageQuery, () => {
    isButtonDisabled.value = imageQuery.content.trim() === "";
}, { deep: true });

// 智能扩写状态
const isExpanding = ref(false);
</script>

<style lang="scss" scoped>
    .layout {
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 10;
            background: linear-gradient(#FCE7CC, #F3F3F3);
            .titleBar {
                display: flex;
                align-items: center;
                padding: 0 30rpx;
                .title {
                    display: flex;
                    align-items: center;
                    padding-left: 200rpx;
                    text {
                        color: #9D9486;
                        font-weight: bold;
                        font-size: 32rpx;
                    }
                }
            }
        }
    }
    
    .style-title {
        padding: 20rpx;
    }
    
    .scroll-view_h {
        white-space: nowrap;
        height: 130rpx;
        .stytle-content {
            height: 130rpx;
            width: 130rpx;
            margin-left: 20rpx;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            .style-list {
                position: relative;
                image {
                    width: 110rpx;
                    height: 110rpx;
                    border-radius: 15rpx;
                    object-fit: cover;
                }
                text {
                    position: absolute;
                    left: 0;
                    right: 0;
                    bottom: 5rpx;
                    font-size: 22rpx;
                    border-bottom-left-radius: 15rpx;
                    border-bottom-right-radius: 15rpx;
                    text-align: center;
                    padding: 5rpx 0;
                    color: #ffffff;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }
        .stytle-content:last-child {
            margin-right: 20rpx;
        }
        .select-style {
            border: 3rpx solid #E23256;
            border-radius: 15rpx;
            box-sizing: border-box;
        }
    }
    
    .ratio-title {
        padding: 20rpx;
    }
    
    .ratio-content {
        height: 80rpx;
        width: 120rpx;
        margin-left: 20rpx;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background-color: #f3f3f3;
        border-radius: 10rpx;
        text {
            font-size: 24rpx;
            color: #333;
        }
    }
    
    .select-ratio {
        border: 2rpx solid blue;
    }
    
    .section {
        margin-bottom: 40rpx;
	    margin-right: 20rpx;
	    margin-left: 20rpx;
        .section-title {
            font-size: 32rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }
        .input-container {
            background-color: #f5f7fa;
            border-radius: 10rpx;
            padding: 20rpx;
            margin-bottom: 20rpx;
            .input-box {
                width: 100%;
                height: 200rpx;
                font-size: 28rpx;
                color: #666;
                overflow: hidden; /* 去掉滚动条 */
                resize: none; /* 去掉调整大小功能 */
            }
            .input-footer {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                margin-top: 10rpx;
                .word-count-container {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                    .ai-expansion {
                        display: flex;
                        align-items: center;
                        cursor: pointer;
                        background: linear-gradient(to right, #E6F7FF, #DEF2FF);
                        border-radius: 40rpx;
                        padding: 6rpx 15rpx;
                        box-shadow: 0 2rpx 8rpx rgba(31, 155, 229, 0.2);
                    }
                    .t {
                        display: flex;
                        align-items: center;
						text{
							font-size: 15px;
							color: #808080;
						}
                    }
                    .ai-text {
                        color: #1F9BE5;
                        font-size: 24rpx;
                        font-weight: 500;
                    }
                    .uni-icons {
                        margin-left: 10rpx;
                    }
                }
            }
        }
    }
    
    // AI生成中提示
    .creative-tips {
		width: 300px;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 100;
        .animating-text {
            font-size: 40rpx;
            font-weight: bold;
            text-align: center;
        }
    }

    .creative-images {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-around;
        margin:20rpx;
        .creative-image {
            position: relative;
            width: 48%;
            margin-bottom: 80px;
            image {
                width: 100%;
                border-radius: 10px;
            }
            .image-actions {
                position: absolute;
                right: 10px;
                top: 50%;
                transform: translateY(-50%);
                display: flex;
                flex-direction: column;
                .action-button {
                    background: rgba(0, 0, 0, 0.5);
                    border-radius: 50%;
                    width: 36px;
                    height: 36px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    margin: 8px 0;
                    cursor: pointer;
                }
            }
        }
    }
    
    // 分享弹窗样式
    .share-content {
        padding: 20px;
        .share-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 20px;
        }
        .share-icons {
            display: flex;
            justify-content: space-around;
            .share-icon {
                display: flex;
                flex-direction: column;
                align-items: center;
                uni-icons {
                    margin-bottom: 5px;
                }
                text {
                    font-size: 14px;
                }
            }
        }
    }
    
    // 去掉button的样式
    button::after {
        border: none;
    }
    
    button {
        padding: 0;
        margin: 0;
        line-height: inherit;
        background-color: #ffffff;
    }
    
    // 给按钮加上样式
    .btn {
        position: fixed;
        bottom: 68rpx;
        left: 20rpx;
        right: 20rpx;
        padding: 20rpx 0;
        border-radius: 40rpx;
        background: linear-gradient(to right, #A2C5FE, #C0E7FD);
    }
    // 禁用按钮的样式
    .btn:disabled {
        background: linear-gradient(to right, #E0E0E0, #F0F0F0);
        opacity: 0.7;
    }
</style>